<?php

namespace app\model;

use think\facade\Db;

class MaterialCategoryModel extends BaseModel
{
    protected $name = 'material_category';


    /**
     * Notes: 每天检测自动预警
     * User: chenLei
     * Date: 9/8/25
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkWarning()
    {
        $list = $this->where('warning_quantity', '>', 0)->select();
        $data = [];
        foreach ($list as $item) {
            if ($item['current_quantity'] <= $item['warning_quantity'] && $item['max_quantity'] > 0 &&
                $item['max_quantity'] > $item['warning_quantity']) {
                $data[] = $item->toArray();
            }
        }


        $res = $this->createPurchase($data);

        return $res;
    }

    /**
     * Notes:系统自动检测
     * User: chenLei
     * Date: 9/8/25
     * @param $data
     * @return bool
     */


    public function createPurchase($data)
    {

        Db::startTrans();
        try {


            $order_no = 'PO' . date('YmdHis') . rand(1000, 9999);
            $order_data = [
                'order_no' => $order_no,
                'supplier_id' => 0,
                'order_date' => date('Y-m-d'),
                'status' => 1,
                'remark' => '系统自动检测，低于预警产品自动生成采购',
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
                'type' => PurchaseOrderModel::TYPE_SYSTEM
            ];
            $order_id = PurchaseOrderModel::insertGetId($order_data);

            $order_detail = [];
            foreach ($data as $item) {
                $quantity = $item['max_quantity'] - $item['current_quantity'];
                if ($quantity > 0) {
                    $order_detail[] = [
                        'order_id' => $order_id,
                        'material_id' => $item['id'],
                        'quantity' => $item['max_quantity'] - $item['current_quantity'],
                        'unit_price' => 0,
                        'amount' => 0,
                        'delivery_date' => null,
                        'remark' => '系统预警自动生成',

                    ];
                }
            }

            if (count($order_detail) <= 0) {
                throw new \Exception('没有生成采购单');
            }
            PurchaseOrderDetailModel::insertAll($order_detail);


            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            $this->error = $exception->getMessage();
            return false;
        }

        return true;

    }


    /**
     * Notes: 销售订单物料不足情况 自动生成 采购订单
     * User: chenLei
     * Date: 9/16/25
     * @param $params
     * @return bool
     */
    public function bomListCg($params)
    {
        Db::startTrans();
        try {


            $order_no = 'PO' . date('YmdHis') . rand(1000, 9999);
            $order_data = [
                'order_no' => $order_no,
                'supplier_id' => 0,
                'order_date' => date('Y-m-d'),
                'status' => 1,
                'remark' => '销售订单不足，自动生成采购订单',
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
                'type' => PurchaseOrderModel::TYPE_SYSTEM
            ];
            $order_id = PurchaseOrderModel::insertGetId($order_data);

            $order_detail = [];
            foreach ($params as $item) {
                $quantity = $item['diff'];

                $order_detail[] = [
                    'order_id' => $order_id,
                    'material_id' => $item['material_id'],
                    'quantity' => $quantity,
                    'unit_price' => 0,
                    'amount' => 0,
                    'delivery_date' => null,
                    'remark' => '销售订单不足，自动生成采购订单',
                ];

            }

            if (count($order_detail) <= 0) {
                throw new \Exception('没有生成采购单');
            }
            PurchaseOrderDetailModel::insertAll($order_detail);


            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            $this->error = $exception->getMessage();
            return false;
        }

        return true;
    }
}